<?php namespace App\Services;

use Illuminate\Support\Facades\Log;
use Monolog\Handler\AbstractProcessingHandler;

class AliyunLogService extends AbstractProcessingHandler
{
    protected $items = [];
    protected $topic;

    /**
     * @var \Aliyun_Log_Client
     */
    protected $client;

    //构造函数
    function __construct()
    {
        parent::__construct();
        $endpoint = config('log.ENDPOINT');
        $accessKeyId = config('log.KEY');
        $accessKey = config('log.SECRET');

        try {
            $this->client = new \Aliyun_Log_Client($endpoint, $accessKeyId, $accessKey);
        } catch (\Aliyun_Log_Exception $e) {
            $this->client = null;
            Log::warn('[AliyunLog]' . $e->getErrorCode() . $e->getErrorMessage());
        }
    }


    /**
     * Writes the record down to the log of the implementing handler
     *
     * @param  array $record
     * @return void
     */
    protected function write(array $record)
    {
        if ($this->client == null) return;

        $item = new \Aliyun_Log_Models_LogItem();
        $item->setContents([
            'level' => $record['level_name'],
            'message' => $record['formatted'],
        ]);
        $item->setTime(time());

        array_push($this->items, $item);
    }

    public function push()
    {
        if ($this->client == null) return;
        if (count($this->items) == 0) return;
        if (!app()->environment('production')) return;

        $project = config('log.PROJECT');
        $store = config('log.STORE');
        $topic = config('log.TOPIC');
        try {
            $request = new \Aliyun_Log_Models_PutLogsRequest($project, $store, $topic, '', $this->items);
            $putLogRespond = $this->client->putLogs($request);
            $this->items = [];
        } catch (\Aliyun_Log_Exception $e) {
            Log::warn('[AliyunLog]' . $e->getErrorCode() . $e->getErrorMessage());
        }
    }
}

